package com.situ.ssm.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.situ.ssm.entity.Course;
import com.situ.ssm.entity.PageBean;
import com.situ.ssm.service.ICourseService;
import com.situ.ssm.vo.CourseSearchCondition;

@Controller
@RequestMapping(value="/course")
public class CourseController {
	
	@Autowired
	private ICourseService courseService;
	
	@RequestMapping(value="/list")
	@ResponseBody
	public List<Course> list() {
		return courseService.list();
	}
	
	@RequestMapping(value="/pageList")
	public String pageList(CourseSearchCondition condition,Model model) {
		if (condition.getPageNo() == null) {
			condition.setPageNo(1);
		}
		if (condition.getPageSize() == null) {
			condition.setPageSize(3);
		}
		PageBean<Map<String, Object>> pageBean = courseService.getPageBean(condition);
		model.addAttribute("pageBean",pageBean);
		System.out.println(pageBean);
		model.addAttribute("condition",condition);
		return "course/course_list";
	}
	
	@RequestMapping(value="/getInsertPage")
	public String getInsertPage() {
		return "course/course_insert";
	}
	
	@RequestMapping(value="/insert")
	@ResponseBody
	public Boolean insert(String name,Integer credit,String classhour) {
		Course course = new Course(name, credit, classhour);
		boolean result = courseService.insert(course);
		return result;
	}
	
	@RequestMapping(value="/deleteById")
	@ResponseBody
	public Boolean deleteById(Integer id) {
		boolean result = courseService.deleteById(id);
		return result;
	}
	
	@RequestMapping(value="/deleteAll")
	@ResponseBody
	public Boolean deleteAll(String[] selectIds) {
		boolean reselt = courseService.deleteAll(selectIds);
		return reselt;
	}
	
	@RequestMapping(value="/toUpdate")
	public String toUpdate(Integer id,Model model) {
		Course course = courseService.findByName(id);
		model.addAttribute("course",course);
		return "course/course_update";
	}
	
	@RequestMapping(value="/update")
	@ResponseBody
	public Boolean update(Integer id,String name,Integer credit,String classhour) {
		Course course = new Course(id, name, credit, classhour);
		boolean result = courseService.update(course);
		return result;
	}
	
	//ajax
	@RequestMapping(value="/checkName")
	public void checkName(String name,HttpServletRequest request,HttpServletResponse response) throws IOException {
		boolean isExist = courseService.checkName(name);
		response.setContentType("text/html;charset = utf-8");
		response.getWriter().write("{\"isExist\": "+isExist+"}");
	}
}
